package com.example.sunjian.myapplication.asynctask;

import android.app.Activity;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.example.sunjian.myapplication.R;

/**
 * 作者：sunjian on 16/7/4 11:08
 * 邮箱：sunjian@cyhz.com
 * AsyncTask 应用demo
 */
public class AsyncTaskDemoActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.async_layout);
       final TextView tex=(TextView)findViewById(R.id.tex);
        final ProgressBar pro =(ProgressBar)findViewById(R.id.pro);
        Log.e("sj","current thread:"+Thread.currentThread());
        new Thread(){//最好不在子线程中new实例，调用execute（）方法
            @Override
            public void run() {
                super.run();
                tex.setText("thread......start");//异步任务执行前，主线程中执行
                MyTask task = new MyTask(tex,pro);
                task.execute();// 该方法不能被多次调用

            }
        }.start();

    }


    class MyTask extends AsyncTask<Integer,Integer,String>{


        private TextView mTex;
        private ProgressBar mPro;
        public MyTask(TextView textView, ProgressBar pro){
            super();
            mTex = textView;
            mPro = pro;
        }


        @Override
        protected void onPreExecute() {
            mTex.setText("onPreExecute......start");//异步任务执行前，主线程中执行
            mTex.setTextColor(Color.parseColor("#ff0000"));
            mTex.setBackgroundColor(Color.parseColor("#a0000000"));
            Log.e("sj","current thread:"+Thread.currentThread());
        }

        @Override
        protected void onPostExecute(String s) {//任务执行完，参数为s是doInBackground 返回的结果，在主线程中执行
            mTex.setText("onPostExecute........end："+s);
            Log.e("sj","current thread:"+Thread.currentThread());
        }

        @Override
        protected void onProgressUpdate(Integer... values) {//更新异步任务执行情况，该方法在主线程中 参数是publishProgress(i)传递过来的

            mTex.setText("onProgressUpdate.......>"+values[0].intValue());
            mPro.setProgress(values[0].intValue());
        }

        @Override
        protected String doInBackground(Integer... params) {//异步线程执行耗时任务    返回结果就是onPostExecute方法的参数
            int i=0;
            try {
                for (i = 10; i < 50; i++) {

                    Thread.sleep(300);
                    publishProgress(i);
                }
            }catch (Exception e){

            }

            return "执行完成";
        }
    }



}
